<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomMessage from './components/RoomMessage.vue'
import RoomAction from './components/RoomAction.vue'
import { nextTick, onMounted, onUnmounted, provide, ref } from 'vue'
import type { Socket } from 'socket.io-client'
import { io } from 'socket.io-client'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import type { Message, TimeMessages } from '@/types/room'
import { MsgType, OrderType } from '@/enum'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { getConsultOrderDetail } from '@/services/consult'
import dayjs from 'dayjs'
import { showToast } from 'vant'

const store = useUserStore()
const route = useRoute()

let socket: Socket
const list = ref<Message[]>([]) // 所有的消息列表数组
const consult = ref<ConsultOrderItem>()
const initialMsg = ref(true) // ,默认是第一次获取聊天记录

// 1. 配置socket.io
onMounted(() => {
  // 参数1：不传默认是当前服务域名，开发中传入服务器地址
  // 参数2：配置参数，根据需要再来介绍
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })

  // 监听连接成功
  socket.on('connect', () => {
    console.log('连接建立成功')
    // 清空聊天记录
    list.value = []
  })
  // 监听错误消息
  socket.on('error', (ev) => {
    console.log('出现错误', ev.error)
  })
  // 监听关闭连接
  socket.on('disconnect', () => {
    console.log('断开连接')
  })
})
onUnmounted(() => {
  // 关闭连接
  socket.close()
})

// 2. 获取聊天记录
onMounted(() => {
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    console.log(data)
    // 2.1 处理消息分组数据
    const arr: Message[] = []
    data.forEach((item, i) => {
      // 2.1.0 取出第一个分组的时间作为下一次请求的开始时间
      if (i === 0) time.value = item.createTime
      // 2.1.1 取出消息分组的时间, 创建一条新的消息
      arr.push({
        id: item.createTime,
        createTime: item.createTime,
        msgType: MsgType.Notify,
        msg: {
          content: item.createTime
        },
        scroll: initialMsg.value
      })
      // 2.2.2 取出消息分组中的其它消息, 从尾部放入数组
      // arr.push(...item.items)
      item.items.forEach((obj) => {
        arr.push({ scroll: initialMsg.value, ...obj })
      })
    })
    // 2.2 把临时数组合并到列表数组中
    list.value.unshift(...arr)
    console.log(list.value)

    // ------------------------------------------
    // 2.3 关闭刷新中效果
    loading.value = false
    // 2.4 判断是否有历史消息
    if (data.length === 0) return showToast('没有更多聊天内容了~')
    // 2.5 判断是否是第一次获取聊天记录
    if (initialMsg.value) {
      nextTick(() => {
        initialMsg.value = false // 不是第一次了
        // 标明历史记录中最后一条消息已读(在它之前的所有消息,服务端都会标明已读)
        socket.emit('updateMsgStatus', arr[arr.length - 1].id)
        window.scrollTo(0, document.body.scrollHeight)
      })
    }
  })
})

// 3. 获取订单状态
onMounted(async () => {
  // 3.1 挂载完成就获取订单状态(初始获取)
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data

  // 3.2 获取服务端告知订单状态发生变化(医生接诊, 医生结束问诊)
  socket.on('statusChange', async () => {
    const res = await getConsultOrderDetail(route.query.orderId as string)
    consult.value = res.data
  })
})

// 4. 发送文字消息
const sendText = (text: string) => {
  // 4.1 给socket服务器发送文字消息
  // 包装一条消息: 发送人id, 接收人id,  msgType,  msg
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content: text
    }
  })
}

// 5. 发送图片消息
const sendImage = (picture: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture
    }
  })
}

// 6. 接收服务端给回的消息
onMounted(() => {
  socket.on('receiveChatMsg', async (data) => {
    // 6.1 把消息添加到列表数组
    list.value.push({ scroll: true, ...data })
    // 6.2 让页面滚动到最底部
    await nextTick()
    // 标明消息已读
    socket.emit('updateMsgStatus', data.id)
    window.scrollTo(0, document.body.scrollHeight)
  })
})

// 7. 下拉刷新
const loading = ref(false)
const time = ref(dayjs().format('YYYY-MM-DD hh:mm:ss'))
const onRefresh = () => {
  console.log('触发下拉刷新了')
  socket.emit('getChatMsgList', 5, time.value, route.query.orderId)
}

// 8. 评分
provide('consult', consult)

const completeEva = (score: number) => {
  // 8.1 要从list列表中找到未评价的这条数据
  const item = list.value.find((obj) => obj.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msgType = MsgType.CardEva // 把消息的类型由未评价变成已评价
    item.msg.evaluateDoc = {
      score
    }
  }
}
provide('completeEva', completeEva)
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="医生问诊室"></cp-nav-bar>
    <room-status
      :status="consult?.status"
      :countdown="consult?.countdown"
    ></room-status>
    <!-- 包装了一个下拉刷新组件 -->
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message :list="list"></room-message>
    </van-pull-refresh>
    <room-action
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="sendText"
      @send-image="sendImage"
    ></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
